package domotica.client;
import java.awt.Dimension;
import java.util.ArrayList;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import domotica.houseowner.HouseOwner;

/**
 * Questa classe effettua un polling periodico del server 
 * per ottenere lo stato (acceso/spento) di tutti i componenti e 
 * visualizzarlo a video.
 */
public class StateThread implements Runnable{

	private HouseOwner houseOwner;
	private JTable jTable;
	
	public StateThread(JTable jTable, HouseOwner houseOwner){
		this.houseOwner=houseOwner;
		this.jTable=jTable;
		this.jTable.setEnabled(false);
	}
	
	public void run() {
		
		int i;
		
		ArrayList<String> names = new ArrayList<String>(houseOwner.getActuatorsSensorsNameList());
		ArrayList<Boolean> states = new ArrayList<Boolean>(houseOwner.areActuatorsSensorsOn());
		Object[][] measures = new Object[states.size()][2];
		
		i=0;
		
		boolean state;
		
		for(String name : names){
			measures[i][0]=name;
			
			state= states.get(i);
			if (state==true)
				measures[i][1]="ON";
			else
				measures[i][1]="OFF";
			i++;
		}
		jTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
        jTable.setFillsViewportHeight(true);
		
		TableModel tableModel= 
			new DefaultTableModel(measures,
					new String[] { "Componente", "Stato" });
		this.jTable.setModel(tableModel);
		
		while(true){
			
			states = new ArrayList<Boolean>(houseOwner.areActuatorsSensorsOn());
			
			i=0;
			
			for(boolean state2 : states){
				
				if (state2==true)
					tableModel.setValueAt("ON", i, 1);
				else
					tableModel.setValueAt("OFF", i, 1);
				i++;
			}
			
			this.jTable.setModel(tableModel);
			
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		
	}

}
